<?php

namespace App\Models\Member;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Models\Member\RelationBackup;
use App\Common\ValidateHandler;
use Carbon\Carbon;
use App\Common\CodeHandler;
use App\Models\Member\Grade;
use App\Models\Member\Order;
use App\Common\AliossHandler;
use App\Models\Member\Store;
use App\Models\Member\DealRecord;
use App\Models\Member\TeamAward;
use App\Models\Member\Member;
use DB, JWTAuth, Auth, Hash, Config;
use App\Common\PayHandler;
use App\Services\SecureTokenService;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $fillable = [
        'id', 'store_id', 'pid','team_id' ,'recom_id','left', 'right', 'level',
        'true_name', 'phone', 'password', 'password_pay', 'weixin', 'grade',
        'nickname', 'avatar', 'open_id', 'union_id', 'gold', 'jf',
        'jgz', 'bd_index', 'is_subscribe', 'subscribe_at', 'is_regist', 'is_active', 'regist_at', 'created_at', 'updated_at'
    ];
    
    protected function serializeDate(\DateTimeInterface $date)
    {
        return Carbon::instance($date)->toDateTimeString();
    }

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    // 用户关注处理, 微信登录逻辑
    public function subscribeAndWxlogin($storeId, $userInfo, $type)
    {   
        // $parentId = 1;
        // DB::beginTransaction();
        // try {
            // $parent = $this->where('id', $parentId)->lockForUpdate()->first()->toarray();
            $user = $this->where('store_id', $storeId)
                         ->where('open_id', $userInfo['openid'])
                         ->first();

            $service = new SecureTokenService();
            if (!empty($user)) {

                $token = JWTAuth::fromUser($user);
                // DB::commit();
                return ['res' => true, 'token' => $token, 'code' => 200];
            }

            // 新用户 - 创建安全令牌
            $secure_token = $service->createOpenidToken($userInfo['openid'],$userInfo['nickname'],$userInfo['headimgurl']);
            // DB::commit();
            return ['res' => true, 'secure_token' => $secure_token, 'code' => 201];
            // $arr = [];
            // $arr['store_id'] = $storeId;
            // $arr['pid'] = $parentId;
            // $arr['left'] = $parent['right'];
            // $arr['right'] = $parent['right'] + 1;
            // $arr['level'] = $parent['level'] + 1;
            // $arr['nickname'] = $userInfo['nickname'];
            // $arr['avatar'] = $userInfo['headimgurl'];
            // $arr['open_id'] = $userInfo['openid'];
            // if ($type == 'subscribe') {
            //     // 关注类型  不存在
            //     $arr['is_subscribe'] = 1;
            //     $arr['subscribe_at'] = date('Y-m-d H:i:s');
            // }

            // $this->where('right', '>=', $parent['right'])->lockForUpdate()->get();
            // DB::update("update users set `left` = if (`left` > {$parent['right']}, `left` + 2, `left`), `right` = if (`right` >= {$parent['right']}, `right` + 2, `right`) where `right` >= {$parent['right']}");

            // $result = $this->create($arr);
            // RelationBackup::create([
            //     'user_id' => $result->id,
            //     'pid' => $parentId,
            //     'parent_all' => "$parentId",
            //     'level' => $result->level,
            //     'type' => $type == 'subscribe' ? 2 : 1
            // ]);
            // if ($type == 'subscribe'){
            //     DB::commit();
            //     return true;
            // }

            // DB::commit();
            // if ($type == 'login') {
            //     $token = JWTAuth::fromUser($result);
            //     return ['res' => true, 'token' => $token];
            // }
        // } catch (\Exception $e) {
        //     DB::rollback();
        // }
    }

    // 用户取消关注
    public function unsubscribe($openId, $storeId)
    {
        $this->where('open_id', $openId)->where('store_id', $storeId)->update(['is_subscribe' => 0]);
    }

    // 用户绑定关系处理逻辑


    public function passwordLogin($storeId, $phone, $password)
    {

        $result = $this->validatePasswordLogin($phone, $password);
        if (!$result['res']) return $result;

        $param = ['phone' => $phone,'password' => $password,'store_id'=>$storeId];
        $token = Auth::attempt($param);
        if($token){
            $user = Auth::user();
            if ($user->store_id != $storeId) return ['res' => false, 'info' => '非此店铺用户'];
            // 检查激活状态
            if (!$user->is_active) return ['res' => false,'info' => '账户未激活，请先绑定微信激活账户'];
            return ['res' => true, 'token' => $token];
        }
        return ['res' => false, 'info' => '用户名或者密码不正确'];
    }

    private function validatePasswordLogin($phone, $password)
    {
        $arr = [
            0 => [
                'name' => '手机',
                'value' => $phone,
                'func' => 'is_phone'
            ],
            1 => [
                'name' => '密码',
                'value' => $password,
                'func' => 'is_empty'
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function codeLogin($storeId, $phone, $code)
    {

        $result = $this->validateCodeLogin($phone, $code);
        if (!$result['res']) return $result;

        $validateCode = CodeHandler::checkCode($storeId, $phone, $code, 'login');
        if (!$validateCode['res']) return ['res' => false, 'info' => $validateCode['info']];

        $user = $this->where('phone', $phone)->first();
        if (empty($user)) return ['res' => false, 'info' => '不存在用户'];
        if ($user->store_id != $storeId)
            return ['res' => false, 'info' => '非此店用户'];
        // 检查激活状态
        if (!$user->is_active) return ['res' => false,'info' => '账户未激活，请先绑定微信激活账户'];
        $token = JWTAuth::fromUser($user);
        return ['res' => true, 'token' => $token];
    }

    private function validateCodeLogin($phone, $code)
    {
        $arr = [
            0 => [
                'name' => '手机',
                'value' => $phone,
                'func' => 'is_phone'
            ],
            1 => [
                'name' => '验证码',
                'value' => $code,
                'func' => 'is_empty'
            ],
            2 => [
                'name' => '验证码',
                'value' => $code,
                'func' => 'length_limit',
                'min' => 6,
                'max' => 6
            ]
        ];
        return ValidateHandler::do($arr);
    }

    // 验证支付密码是否存在
    public function isPayPassword($id)
    {
        return $this->where('id', $id)->select('password_pay')->first();
    }

    // 设置支付密码 
    public function setPayPassword($id, $passwordPay)
    {
        $result = $this->validatePayPassword($passwordPay);
        if (!$result['res']) {
            return [
                'info' => $result['info'],
                'data' => 0,
                'code' => 20001
            ];
        }
        $data = $this->where('id', $id)->update(['password_pay' => Hash::make($passwordPay)]);
        if ($data) {
            return [
                'info' => '支付密码设置成功',
                'data' => 1,
                'code' => 20000
            ];
        } else {
            return [
                'info' => '支付密码设置失败',
                'data' => 0,
                'code' => 20001
            ];
        }
    }

    private function validatePayPassword($passwordPay)
    {
        $arr = [
            0 => [
                'name' => '支付密码',
                'value' => $passwordPay,
                'func' => 'length_limit',
                'min' => 6,
                'max' => 6
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function bind($storeId, $pid, $userInfo, $data)
    {       
        //验证数据规范性
        $data['code'] = $data['phonecode'];
        $result = $this->validatePassword($data);
        if (!$result['res']) return $result;
        //验证短信验证码
        $validateCode = CodeHandler::checkCode($data['storeId'], $data['phone'], $data['code'], $data['handlerType']);
        if (!$validateCode['res']) return ['res' => false, 'info' => $validateCode['info']];

        DB::beginTransaction();
        try {
            $parent = $this->where('id', '>', 1)->where('id', $pid)->lockForUpdate()->first();
            if(empty($parent)) return ['res' => false, 'info' => '推荐人无效'];
            if($parent->store_id != $storeId) return ['res' => false, 'info' => '推荐人店铺无效'];

            $user = $this->where('store_id', $storeId)
                         ->where('open_id', $userInfo['openid'])
                         ->lockForUpdate()
                         ->first();

            if (!empty($user)) {
                if ($user->id == $pid)
                    return ['res' => false, 'info' => '自己不能推荐自己'];
                if ($user->is_regist)
                    return ['res' => false, 'info' => '已绑定关系'];
                $this->handleBandParent($parent);

                if ($parent->left > $user->left) {
                    // 向右移动
                    $this->where('left', '>=', $user->left)->where('left', '<=', $parent->right)->lockForUpdate()->get();
                    // 修改左右值
                    DB::update("update users set `left` = if (`left` > {$user->left} and `left` < {$parent->right}, -`left` + 2, -{$parent->right} + 2) where `left` >= {$user->left} and `left` <= {$parent->right}");
                    DB::update("update users set `right` = if (`right` > {$user->right} and `right` < {$parent->right}, -`right` + 2, -{$parent->right} + 1) where `right` >= {$user->right} and `right` < {$parent->right}");
                } else {
                    // 向左移动
                    $this->where('right', '>=', $parent->right)->where('right', '<', $user->right)->lockForUpdate()->get();
                    // 修改左右值
                    DB::update("update users set `left` = if (`right` > {$parent->right} and `left` > {$parent->left} and `right` < {$user->right}, -`left` - 2, `left`), `right` = if (`right` >= {$parent->right} and `right` < {$user->right}, -`right` - 2, `right`) where `right` >= {$parent->right} and `right` < $user->right");
                    $user->left = $parent->right;
                    $user->right = $parent->right + 1;
                }
                $data = $this->select(['id', 'left', 'right'])->get()->toArray();

                $user->nickname = $userInfo['nickname'];
                $user->avatar = $userInfo['headimgurl'];
                $user->is_regist = 1;
                $user->is_active = 1;
                $user->regist_at = date('Y-m-d H:i:s');
                $user->pid = $pid;
                $user->team_id = $parent->team_id;
                $user->recom_id = $parent->recom_id;
                $user->level = $parent->level + 1;
                $user->save();

                DB::update("update users set `right` = -`right` where `right` < 0 ");
                DB::update("update users set `left` = -`left` where `left` < 0 ");

                //修改备份关系
                $parentRelationBackup = RelationBackup::where('user_id', $pid)->first();
                $relationBackup = RelationBackup::where('user_id', $user->id)->first();
                $relationBackup->parent_all = $parentRelationBackup->parent_all . "-$pid";
                $relationBackup->level = $parentRelationBackup->level + 1;
                $relationBackup->type = 3;
                $relationBackup->save();

                //openid和手机号密码都存在 注册完成生成推荐积分
                $DealRecord = new DealRecord;
                $dealGold = [];
                $dealGold['store_id'] = $storeId;
                $dealGold['status'] = 3;
                $dealGold['deal_item_id'] = 0;
                $dealGold['deal_user_id'] = $user->id;
                $dealGold['order_type'] = 10;
                $dealGold['jm_type'] = 2;
                $dealGold['user_id'] = $pid;
                $dealGold['grade'] = $parent->grade;
                $dealGold['mark'] = 0;
                $dealGold['amount'] = Config::get('const.jf_rec');
                $dealGold['reason'] = '推荐积分';
                $dealGold['deal_type'] = 13;
                $goldDeduct = $DealRecord->returnedMoney($dealGold);
                if ($goldDeduct['code'] != 20000) {
                    return ['res' => false, 'info' => $goldDeduct['info']];
                }

                $token = JWTAuth::fromUser($user);
                
                DB::commit();
                return ['res' => true, 'token' => $token];
            }
            //用户不存在时验证手机号是否注册 存在后台导入用户已注册手机号
            $this->handleBandParent($parent);
            
            $userPhone = $this->where('store_id', $storeId)
                         ->where('phone', $data['phone'])
                         ->lockForUpdate()
                         ->first();
            if(!empty($userPhone)) return ['res' => false, 'info' => '该手机号已被使用'];
            $arr = [];
            $arr['store_id'] = $storeId;
            $arr['pid'] = $pid;
            $arr['team_id'] = $parent->team_id;
            $arr['recom_id'] = $parent->recom_id;
            $arr['left'] = $parent->right;
            $arr['right'] = $parent->right + 1;
            $arr['level'] = $parent->level + 1;
            $arr['nickname'] = $userInfo['nickname'];
            $arr['avatar'] = $userInfo['headimgurl'];
            $arr['open_id'] = $userInfo['openid'];
            $arr['phone'] = $data['phone'];
            $arr['password'] = Hash::make($data['password']);
            $arr['is_regist'] = 1;
            $arr['is_active'] = 1;
            $arr['regist_at'] = date('Y-m-d H:i:s');
            
            $this->where('right', '>=', $parent->right)->lockForUpdate()->get();
            DB::update("update users set `left` = if (`left` > {$parent->right}, -`left` - 2, `left`), `right` = if (`right` >= {$parent->right}, -`right` - 2, `right`) where `right` >= {$parent->right}");

            DB::update("update users set `right` = -`right` where `right` < 0 ");
            DB::update("update users set `left` = -`left` where `left` < 0 ");

            $parentRelationBackup = RelationBackup::where('user_id', $pid)->first();

            $result = $this->create($arr);
            RelationBackup::create([
                'user_id' => $result->id,
                'pid' => $pid,
                'parent_all' => $parentRelationBackup->parent_all . "-$pid",
                'level' => $result->level,
                'type' => 3
            ]);
            //发放注册积分和推荐积分 
            $jfResult = $this->registJf($data,$result);
            if(!$jfResult['res']) return $jfResult;

            DB::commit();
            $token = JWTAuth::fromUser($result);
            return ['res' => true, 'token' => $token];
        } catch (\Exception $e) {
            DB::rollback();
            return ['res' => false, 'info' => '操作失败'.$e->getLine().$e->getMessage()];
        }
    }

    public function gradeNum($user, $grade)
    {
        return $this->where('left', '>', $user['left'])->where('right', '<', $user['right'])->where('grade', $grade)->count();
    }
    
    private function handleBandParent($parent)
    {
        if (!$parent->is_regist) {
            // 绑定上级为未注册用户  改为已注册用户 此时这个推荐人不可以再绑定关系了
            $parent->is_regist = 1;
            $parent->regist_at = date('Y-m-d H:i:s');
            $parent->save();
        }
    }

    public function getFansList($request)
    {   
        //只显示直推用户
        $user = Auth::user()->toArray();
        $data = $this->where('pid', $user['id']);
                // ->where('team_id',$user['team_id']);

        if (!empty($request['word'])) {
            $data->where(function($query) use ($request){
                $query->where('phone', 'like', '%'.$request['word'].'%')->orWhere('weixin', 'like', '%'.$request['word'].'%');
            });
        }

        $data = $data->orderBy('left', 'desc')
                ->paginate(10)
                ->toArray();

        return $data;
    }

    public function getFansDetail($fansId)
    {
        $user = Auth::user()->toArray();
        $fans = $this->find($fansId)->toArray();
        $data = $this->where('left', '>', $user['left'])
                     ->where('left', '<=', $fans['left'])
                     ->where('right', '<', $user['right'])
                     ->where('right', '>=', $fans['right'])
                     ->orderBy('level', 'desc')
                     ->paginate(10)
                     ->toArray();

        return $data;
    }

    public function fansManage()
    {
        $data = [];
        $user = Auth::user()->toArray();
        // $today = Carbon::today();
        // $startOfWeek = Carbon::now()->startOfWeek();
        // $endOfWeek = Carbon::now()->endOfWeek();
        // $startOfMonth = Carbon::now()->startOfMonth();
        // $endOfMonth = Carbon::now()->endOfMonth();
        $data['all'] = $this->where('left', '>', $user['left'])
                     ->where('right', '<', $user['right'])
                     ->where('team_id', $user['team_id'])
                     ->count();
        $data['direct'] = $this->where('left', '>', $user['left'])
                     ->where('right', '<', $user['right'])
                     ->where('pid', $user['id'])
                     ->count();
        // $data['this_month'] = $this->where('left', '>', $user['left'])
        //              ->where('right', '<', $user['right'])
        //              ->where('team_id', $user['team_id'])
        //              ->whereBetween('created_at', [$startOfMonth,$endOfMonth])
        //              ->count();
        // $data['this_week'] = $this->where('left', '>', $user['left'])
        //              ->where('right', '<', $user['right'])
        //              ->where('team_id', $user['team_id'])
        //              ->whereBetween('created_at', [$startOfWeek,$endOfWeek])
        //              ->count();
        // $data['today'] = $this->where('left', '>', $user['left'])
        //              ->where('right', '<', $user['right'])
        //              ->where('team_id', $user['team_id'])
        //              ->whereDate('created_at', $today)
        //              ->count();

        // $start=Carbon::now()->startOfWeek();
        // $end=Carbon::now()->endOfWeek();
        return $data;
    }

    public function updateNickname($nickname)
    {
        $result = $this->validateNickname($nickname);
        if (!$result['res']) return $result;

        $user = Auth::user();
        $user->nickname = $nickname;
        $user->save();

        return ['res' => true];
    }

    private function validateNickname($nickname)
    {
        $arr = [
            0 => [
                'name' => '昵称',
                'value' => $nickname,
                'func' => 'is_empty'
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function updateName($name,$idCard)
    {
        $result = $this->validateName($name,$idCard);
        if (!$result['res']) return $result;

        $user = Auth::user();
        if(!empty($user->true_name) && !empty($user->idcard)){
            return ['res' => false,'info' => '姓名及身份证号码已存在'];
        }
        $user->true_name = $name;
        $user->idcard = $idCard;
        $user->save();

        return ['res' => true];
    }

    private function validateName($name,$idCard)
    {
        $arr = [
            0 => [
                'name' => '姓名',
                'value' => $name,
                'func' => 'is_empty'
            ],
            1 => [
                'name' => '身份证号码',
                'value' => $idCard,
                'func' => 'is_card'
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function setPhone($code, $phone)
    {
        $result = $this->validateData($code, $phone);
        if (!$result['res']) return $result;

        $user = Auth::user();
        $storeId = $user->store_id;
        $validateCode = CodeHandler::checkCode($storeId, $phone, $code, 'reset');
        if (!$validateCode['res']) return ['res' => false, 'info' => $validateCode['info']];

        $user->phone = $phone;
        $user->save();
        return ['res' => true];
    }

    private function validateData($code, $phone)
    {
        $arr = [
            0 => [
                'name' => '手机',
                'value' => $phone,
                'func' => 'is_empty'
            ],
            1 => [
                'name' => '手机',
                'value' => $phone,
                'func' => 'is_phone'
            ],
            2 => [
                'name' => '验证码',
                'value' => $code,
                'func' => 'is_empty'
            ],
            3 => [
                'name' => '验证码',
                'value' => $code,
                'func' => 'length_limit',
                'min' => 6,
                'max' => 6
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function setWechat($wechat)
    {
        $result = $this->validateWechat($wechat);
        if (!$result['res']) return $result;

        $user = Auth::user();
        $user->weixin = $wechat;
        $user->save();

        return ['res' => true];
    }

    private function validateWechat($wechat)
    {
        $arr = [
            0 => [
                'name' => '微信号',
                'value' => $wechat,
                'func' => 'is_empty'
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function recommend()
    {
        $user = Auth::user()->toArray();
        $data = $this->where('left', '<', $user['left'])
                     ->where('right', '>', $user['right'])
                    //  ->where('level', '>', 0)
                     ->orderBy('level', 'desc')
                     ->take(1)
                     ->get()
                     ->toArray();

        return $data;
    }


    //逻辑更改 后续优化 忘记密码/设置密码/微信登录创建用户/微信登录激活用户
    public function setPassword($data)
    {
        if ($data['handlerType'] == 'setpwd') {
            $user = Auth::user();
            $data['storeId'] = $user->store_id;
        }

        $result = $this->validatePassword($data);
        if (!$result['res']) return $result;

        $validateCode = CodeHandler::checkCode($data['storeId'], $data['phone'], $data['code'], $data['handlerType']);
        if (!$validateCode['res']) return ['res' => false, 'info' => $validateCode['info']];
        $user = $this->where('store_id', $data['storeId'])
                                ->where('phone', $data['phone'])
                                ->first();
        DB::beginTransaction();
        try {   
                if($data['handlerType'] == 'setpwd' || $data['handlerType'] == 'forget') {
                    
                    $user->password = Hash::make($data['password']);
                    $user->save();
                    DB::commit();
                    return ['res' => true, 'code' => 201];
                }
                
                $param = ['phone' => $data['phone'],'password' => $data['password'],'store_id'=>$data['storeId'],'is_active'=>0];
                $activeUser = Auth::attempt($param);
                $resultInfo = $activeUser ? $this->activeUser($data) : $this->createUser($data);
    
                if(!$resultInfo['res']) return $resultInfo;
                
                $token = JWTAuth::fromUser($resultInfo['info']);
                
                DB::commit();
                return ['res' => true, 'token' => $token, 'code' => 200];
        } catch (\Exception $e) {
            DB::rollback();
            return ['res' => false, 'info' => '操作失败'.$e->getLine().$e->getMessage()];
        }
        
    }

    //用户激活  完善open ID，发放注册积分和推荐积分
    public function activeUser($data){
        // 解析安全令牌
        $service = new SecureTokenService();
        $tokenData = $service->parseOpenidToken($data['secure_token']);
        if (!$tokenData || !isset($tokenData['openid'])) return ['res' => false, 'info' => '安全令牌无效或已过期'];
        $user = $this->where('phone',$data['phone'])->first();
        if(empty($user) || $user['is_active']) return ['res' => false, 'info' => '请输入待激活的账号信息'];

        $old_user = 0;
        $member = new Member;
        $oldUser = $member->where('phone',$data['phone'])->first();
        if(!empty($oldUser)){
            $old_user = 1;
        }

        $user->phone = $data['phone'];
        $user->open_id = $tokenData['openid'];
        $user->nickname = $tokenData['nickname'];
        $user->avatar = $tokenData['avatar'];
        $user->password = Hash::make($data['password']);
        $user->is_active = 1;
        $user->old_user = $old_user;
        $user->save();

        $result = $this->registJf($data,$user);
        return $result;
    }
    //创建用户  注册open ID，手机号，密码等用户信息，发放注册积分
    public function createUser($data){
        // 解析安全令牌
        $service = new SecureTokenService();
        $tokenData = $service->parseOpenidToken($data['secure_token']);
        if (!$tokenData || !isset($tokenData['openid'])) return ['res' => false, 'info' => '安全令牌无效或已过期'];
        $openid = $tokenData['openid'];
        $user = $this->where('open_id',$openid)->first();
        if(!empty($user)) return ['res' => false, 'info' => '该用户信息已存在'];
        $phone = $this->where('phone',$data['phone'])->first();
        if(!empty($phone)) return ['res' => false, 'info' => '该手机号已存在'];

        $parentId = 1;
        $parent = $this->where('id', $parentId)->lockForUpdate()->first()->toarray();
        $arr = [];

        $old_user = 0;
        $member = new Member;
        $oldUser = $member->where('phone',$data['phone'])->first();
        if(!empty($oldUser)){
            $old_user = 1;
        }

        $arr['store_id'] = $data['storeId'];
        $arr['pid'] = $parentId;
        $arr['left'] = $parent['right'];
        $arr['right'] = $parent['right'] + 1;
        $arr['level'] = $parent['level'] + 1;
        $arr['nickname'] = $tokenData['nickname'];
        $arr['avatar'] = $tokenData['avatar'];
        $arr['open_id'] = $tokenData['openid'];
        $arr['phone'] = $data['phone'];
        $arr['password'] = Hash::make($data['password']);
        $arr['old_user'] = $old_user;
        $arr['is_active'] = 1;

        $this->where('right', '>=', $parent['right'])->lockForUpdate()->get();
        DB::update("update users set `left` = if (`left` > {$parent['right']}, `left` + 2, `left`), `right` = if (`right` >= {$parent['right']}, `right` + 2, `right`) where `right` >= {$parent['right']}");

        $result = $this->create($arr);
        RelationBackup::create([
            'user_id' => $result->id,
            'pid' => $parentId,
            'parent_all' => "$parentId",
            'level' => $result->level,
            'type' => 1
        ]);
        
        $result = $this->registJf($data,$result);
        return $result;
    }

    //创建用户 获得注册积分 非公司账号推荐人获得推荐积分
    public function registJf($data, $user){
        $DealRecord = new DealRecord;
        $dealGold = [];
        $dealGold['store_id'] = $data['storeId'];
        $dealGold['status'] = 3;
        $dealGold['deal_item_id'] = 0;
        $dealGold['order_type'] = 9;
        $dealGold['jm_type'] = 2;
        $dealGold['user_id'] = $user->id;
        $dealGold['grade'] = 0;
        $dealGold['mark'] = 0;
        $dealGold['amount'] = Config::get('const.jf_reg');
        $dealGold['reason'] = '注册积分';
        $dealGold['deal_type'] = 12;
        $goldDeduct = $DealRecord->returnedMoney($dealGold);
        if ($goldDeduct['code'] != 20000) {
            return ['res' => false, 'info' => $goldDeduct['info']];
        }
        $parent = $this->where('id',$user->pid)->first();
        if($parent->id != 1){
            $dealGold['deal_user_id'] = $user->id;
            $dealGold['order_type'] = 10;
            $dealGold['user_id'] = $user->pid;
            $dealGold['grade'] = $parent->grade;
            $dealGold['amount'] = Config::get('const.jf_rec');
            $dealGold['deal_type'] = 13;
            $dealGold['reason'] = '推荐积分';
            $goldDeduct = $DealRecord->returnedMoney($dealGold);
            if ($goldDeduct['code'] != 20000) {
                return ['res' => false, 'info' => $goldDeduct['info']];
            }
            //推荐人获取积分 判断是否达到升级标准
            $grade = new Grade;
            $memGrades = $grade->storeGrade($data['storeId']);
            $partnerGrade = $grade->where('store_id',$data['storeId'])->orderBy('level','desc')->first();

            if($parent['grade']+1 < $partnerGrade['level']){
                $info = $grade->where('store_id',$data['storeId'])->where('level',$parent['grade'] + 1)->first();
                $gradeResult = PayHandler::checkRecommend($parent,json_decode($info['recommend'], 1),$info['level'],$info['jf'],0);
                if ($gradeResult['code'] != 20000) {
                    return ['res' => false, 'info' => $gradeResult['info']];
                }
            }
        }
        return ['res' => true,'info' => $user];
    }

    private function validatePassword($data)
    {
        $arr = [
            0 => [
                'name' => '手机号',
                'value' => $data['phone'],
                'func' => 'is_empty'
            ],
            1 => [
                'name' => '手机号',
                'value' => $data['phone'],
                'func' => 'is_phone'
            ],
            2 => [
                'name' => '验证码',
                'value' => $data['code'],
                'func' => 'is_empty'
            ],
            3 => [
                'name' => '验证码',
                'value' => $data['code'],
                'func' => 'length_limit',
                'min' => 6,
                'max' => 6
            ],
            4 => [
                'name' => '密码',
                'value' => $data['password'],
                'func' => 'is_empty'
            ],
            5 => [
                'name' => '密码',
                'value' => $data['password'],
                'func' => 'length_limit',
                'min' => 8,
                'max' => 16 
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function setPasswordByOrigin($data)
    {
        $result = $this->validatePasswordByOrigin($data);
        if (!$result['res']) return $result;

        $user = Auth::user();
        if (!Hash::check($data['origin_password'], $user->password)) {
            return ['res' => false, 'info' => '原密码不正确'];
        }
        $user->password = Hash::make($data['password']);
        $user->save();

        return ['res' => true];
    }

    private function validatePasswordByOrigin($data)
    {
        $arr = [
            1 => [
                'name' => '原密码',
                'value' => $data['origin_password'],
                'func' => 'is_empty'
            ],
            2 => [
                'name' => '密码',
                'value' => $data['password'],
                'func' => 'is_empty'
            ],
            3 => [
                'name' => '密码',
                'value' => $data['password'],
                'func' => 'length_limit',
                'min' => 8,
                'max' => 16 
            ]
        ];
        return ValidateHandler::do($arr);
    }

    public function getUserInfo()
    {
        $user = Auth::user()->toArray();
        $user['gold'] = $user['gold'] / 100;
        $user['jgz'] = $user['jgz'] / 100;
        $user['bd_index'] = $user['bd_index'] / 100;
        $user['jf'] = $user['jf'] / 100;

        $user['gradeTitle'] = Grade::where('store_id', $user['store_id'])->where('level', $user['grade'])->first()->toArray()['title'];
        $user['wait_pay_order'] = Order::where('store_id', $user['store_id'])->where('user_id', $user['id'])->where('order_status', 2)->count();
        $user['wait_send_order'] = Order::where('store_id', $user['store_id'])->where('user_id', $user['id'])->where('order_status', 3)->count();
        
        $teamAward = new TeamAward;    
        $team = $teamAward->storeTeamAward($user['store_id']);
        $user['awardName'] = $team->award_name;
        $user['bdAwardName'] = $team->bd_award_name;
        return $user;
    }

    public function setAvatar($data)
    {
        $result = AliossHandler::upload('avatar', '.jpg');
        
        $user = Auth::user();
        $user->avatar = $result;
        $user->save();

        return ['res' => true];
    }

    public function getParentInfo($id)
    {
        $data = $this->where('id', $id)->select(['nickname','avatar'])->first()->toArray();

        return $data;
    }

    public function getStoreInfo($storeId)
    {
        $data = Store::where('id', $storeId)->first()->title;

        return $data;
    }

    public function directNum($user)
    {
        return $this->where('left', '>', $user['left'])->where('right', '<', $user['right'])->where('pid', $user['id'])->count();
    }

    public function teamNum($user){
        return $this->where('left', '>=', $user['left'])->where('right', '<=', $user['right'])->where('team_id', $user['id'])->count();
    }
}
